package com.aids_malaria.ui.setting;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.adapter.AccountManagerAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.util.LiteOrmUtil;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.MultiDeleteUser;
import com.aids_malaria.http.response.User;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AccountManagerSettingActivity extends BaseActivity implements AccountManagerAdapter.Option {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.cb_check_all)
    CheckBox cb_check_all;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<User> mData = new ArrayList<>();
    private List<User> mOriginalData = new ArrayList<>();
    private AccountManagerAdapter accountManagerAdapter;

    private String mUserCode;
    private String mUserName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_account_manager_setting;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.setting_account_manage));
        initRefreshLayout();
        cb_check_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = cb_check_all.isChecked();
                for (int i=0; i<mData.size(); i++){
                    mData.get(i).setCheck(checked);
                    accountManagerAdapter.notifyDataSetChanged();
                }
            }
        });
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String inputStr = charSequence.toString();
                mData.clear();
                for(int j=0; j<mOriginalData.size(); j++){
                    if(mOriginalData.get(j).getUser_name().contains(inputStr)){
                        mData.add(mOriginalData.get(j));
                    }
                }
                accountManagerAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();
//        mUserCode = SpUtil.getString(mContext, Constant.USER_ACCOUNT,"");
        mUserCode = "";
        mUserName = "";
        if (AuthUtil.isHaveQueryAuthByCode(Constant.SETTING_ROLE_MANAGER)){
            getUser();
        }

    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                getUser();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getUser();
            }
        });
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        accountManagerAdapter = new AccountManagerAdapter(mContext,R.layout.item_account_manager,mData,this);
        rv_data.setAdapter(accountManagerAdapter);
        accountManagerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putBoolean(AccountManagerCreateEditActivity.KEY_IS_CREATE, false);
                bundle.putSerializable(AccountManagerCreateEditActivity.KEY_USER,mData.get(position));
                startActivityForResult(AccountManagerCreateEditActivity.class,200,bundle);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200){
            refresh_layout.autoRefresh();
        }
    }

    @OnClick({R.id.iv_add, R.id.iv_subtract})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_add:
                Bundle bundle = new Bundle();
                bundle.putBoolean(AccountManagerCreateEditActivity.KEY_IS_CREATE, true);
                if (!AuthUtil.isHaveInsertAuthByCode(Constant.SETTING_ROLE_MANAGER)){
                    ToastUtil.showNoPermission();
                }
                startActivity(AccountManagerCreateEditActivity.class,bundle);
                break;
            case R.id.iv_subtract:
                if (!AuthUtil.isHaveDeleteAuthByCode(Constant.SETTING_ROLE_MANAGER)){
                    ToastUtil.showNoPermission();
                }
                List<MultiDeleteUser> multiDeleteUserList = new ArrayList<>();
                for (int i=0; i<mData.size(); i++){
                    if(mData.get(i).isCheck()){
                        MultiDeleteUser multiDeleteUser = new MultiDeleteUser();
                        multiDeleteUser.setUser_code(mData.get(i).getUser_code());
                        multiDeleteUserList.add(multiDeleteUser);
                    }
                }
                if(multiDeleteUserList.size()>0){
                    String dataJson = GsonUtil.beanToJson(multiDeleteUserList);
                    LogUtil.d("dataJson:-----------"+ dataJson);
                    multiDeleteUser(dataJson);
                }else{
                    ToastUtil.showToast(getString(R.string.delete_null));
                }
                break;
        }
    }

    /**
     * 获取用户列表数据
     *
     */
    private void getUser() {
        if (!AuthUtil.isHaveQueryAuthByCode(Constant.SETTING_ROLE_MANAGER)){
            ToastUtil.showNoPermission();
            return;
        }
        mUserName = et_name.getText().toString().trim();
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getUser(mUserCode, mUserName)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<User>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<User> data) throws Exception {
                        mData.clear();
                        mData.addAll(data);
                        mOriginalData.clear();
                        mOriginalData.addAll(data);
                        accountManagerAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 删除多个用户
     * @param data 数据格式举例：[{"user_code":"test123123"},{"user_code":"test900"}]
     * @return
     */
    private void multiDeleteUser(String data) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).multiDeleteUser(requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(getString(R.string.operate_success));
                        getUser();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    @Override
    public void onItemCheck(int position, boolean isCheck) {
        mData.get(position).setCheck(isCheck);
        int totalselect = 0;
        for (int i = 0; i < mData.size() ; i++) {
            if (mData.get(i).isCheck()){
                totalselect++;
            }
        }
        if (totalselect < mData.size() ){
            cb_check_all.setChecked(false);
        }
    }

}
